from flask import Blueprint, jsonify, request
from app.config.config import Config
from app.utils.file_handler import FileHandler
import os
import json
import uuid

form_bp = Blueprint('form', __name__)
file_handler = FileHandler()

# 确保数据目录存在
os.makedirs('data/forms', exist_ok=True)
os.makedirs('data/forms_data', exist_ok=True)

# 仪表盘结构文件路径
DASHBOARD_STRUCTURE_FILE = os.path.join('data', 'dashboard_structure.json')

def generate_form_id():
    """生成唯一的表单ID"""
    return f"form{uuid.uuid4().hex[:8]}"

def update_nav_data(form_id):
    """更新导航栏数据，移除被删除的表单"""
    try:
        nav_file = os.path.join(Config.DATA_DIR, 'nav_structure.json')
        if not os.path.exists(nav_file):
            return False
            
        # 读取导航数据
        with open(nav_file, 'r', encoding='utf-8') as f:
            nav_data = json.load(f)
            
        # 递归查找并删除表单
        def remove_form_from_folder(folder):
            if 'forms' in folder:
                folder['forms'] = [f for f in folder['forms'] if f.get('id') != form_id]
            if 'children' in folder:
                for child in folder['children']:
                    remove_form_from_folder(child)
                    
        # 遍历所有文件夹
        for folder in nav_data:
            remove_form_from_folder(folder)
            
        # 保存更新后的导航数据
        with open(nav_file, 'w', encoding='utf-8') as f:
            json.dump(nav_data, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"更新导航数据错误: {str(e)}")
        return False

@form_bp.route('/<form_id>', methods=['GET', 'POST', 'DELETE'])
def handle_form(form_id):
    # 如果是中文名称，尝试从dashboard_structure中查找对应的form_id
    if not form_id.startswith('form'):
        with open(DASHBOARD_STRUCTURE_FILE, 'r', encoding='utf-8') as f:
            dashboard_structure = json.load(f)
            for dashboard in dashboard_structure:
                for form in dashboard.get('forms', []):
                    if form['name'] == form_id:
                        form_id = form['id']
                        break
                if form_id.startswith('form'):
                    break
    
    form_file = os.path.join('data/forms', f'{form_id}.json')
    
    if request.method == 'GET':
        if os.path.exists(form_file):
            with open(form_file, 'r', encoding='utf-8') as f:
                form_data = json.load(f)
            return jsonify({
                'code': 0,
                'message': 'success',
                'data': form_data
            })
        else:
            return jsonify({
                'code': 404,
                'message': '表单不存在'
            }), 404
            
    elif request.method == 'POST':
        form_data = request.get_json()
        os.makedirs('data/forms', exist_ok=True)
        with open(form_file, 'w', encoding='utf-8') as f:
            json.dump(form_data, f, ensure_ascii=False, indent=2)
        return jsonify({
            'code': 0,
            'message': 'success'
        })
        
    elif request.method == 'DELETE':
        if os.path.exists(form_file):
            try:
                os.remove(form_file)
                return jsonify({
                    'code': 0,
                    'message': '表单删除成功'
                })
            except Exception as e:
                return jsonify({
                    'code': 500,
                    'message': f'删除表单失败: {str(e)}'
                }), 500
        else:
            return jsonify({
                'code': 404,
                'message': '表单不存在'
            }), 404

@form_bp.route('/data/<form_name>', methods=['POST'])
def save_form_data(form_name):
    try:
        # 确保表单数据目录存在
        forms_data_dir = os.path.join('data', 'forms_data')
        if not os.path.exists(forms_data_dir):
            os.makedirs(forms_data_dir)
        
        # 获取请求数据
        form_data = request.json
        
        # 构建文件路径
        file_path = os.path.join(forms_data_dir, f'{form_name}.json')
        
        # 如果文件已存在，读取现有数据
        existing_data = []
        if os.path.exists(file_path):
            with open(file_path, 'r', encoding='utf-8') as f:
                existing_data = json.load(f)
        
        # 为新数据添加ID
        form_data['id'] = str(len(existing_data) + 1)  # 简单的自增ID
        
        # 添加新的提交数据
        existing_data.append(form_data)
        
        # 保存更新后的数据
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(existing_data, f, ensure_ascii=False, indent=2)
        
        return jsonify({
            'code': 0,
            'message': '表单数据保存成功',
            'data': None
        })
    except Exception as e:
        return jsonify({
            'code': 1,
            'message': f'保存表单数据失败: {str(e)}',
            'data': None
        }), 500

@form_bp.route('/data/<form_id>', methods=['GET'])
def get_form_data(form_id):
    try:
        # 确保表单数据目录存在
        forms_data_dir = os.path.join('data', 'forms_data')
        if not os.path.exists(forms_data_dir):
            os.makedirs(forms_data_dir)
        
        # 构建文件路径
        file_path = os.path.join(forms_data_dir, f'{form_id}.json')
        
        # 如果文件存在，返回数据
        if os.path.exists(file_path):
            with open(file_path, 'r', encoding='utf-8') as f:
                form_data = json.load(f)
            return jsonify({
                'code': 0,
                'message': 'success',
                'data': form_data
            })
        else:
            return jsonify({
                'code': 0,
                'message': 'success',
                'data': []
            })
    except Exception as e:
        return jsonify({
            'code': 1,
            'message': f'获取表单数据失败: {str(e)}',
            'data': None
        }), 500

@form_bp.route('/data/<form_id>/<data_id>', methods=['DELETE'])
def delete_form_data(form_id, data_id):
    try:
        # 确保表单数据目录存在
        forms_data_dir = os.path.join('data', 'forms_data')
        file_path = os.path.join(forms_data_dir, f'{form_id}.json')
        
        if not os.path.exists(file_path):
            return jsonify({
                'code': 404,
                'message': '表单数据不存在'
            }), 404
        
        # 读取现有数据
        with open(file_path, 'r', encoding='utf-8') as f:
            form_data = json.load(f)
        
        # 找到并删除指定的数据
        form_data = [item for item in form_data if str(item.get('id')) != str(data_id)]
        
        # 保存更新后的数据
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(form_data, f, ensure_ascii=False, indent=2)
        
        return jsonify({
            'code': 0,
            'message': '删除成功'
        })
    except Exception as e:
        return jsonify({
            'code': 1,
            'message': f'删除表单数据失败: {str(e)}'
        }), 500

@form_bp.route('', methods=['GET'])
def get_all_forms():
    try:
        # 从dashboard_structure.json中获取所有表单信息
        with open(DASHBOARD_STRUCTURE_FILE, 'r', encoding='utf-8') as f:
            dashboard_structure = json.load(f)
        
        # 收集所有表单
        forms = []
        for dashboard in dashboard_structure:
            # 收集当前层级的表单
            if 'forms' in dashboard:
                forms.extend(dashboard['forms'])
            # 递归收集子文件夹中的表单
            if 'children' in dashboard:
                for child in dashboard['children']:
                    if 'forms' in child:
                        forms.extend(child['forms'])
        
        return jsonify({
            'code': 0,
            'message': 'success',
            'data': forms
        })
    except Exception as e:
        print(f"Error getting forms: {str(e)}")
        return jsonify({
            'code': 500,
            'message': '获取表单列表失败'
        }), 500

@form_bp.route('/list', methods=['GET'])
def get_forms_list():
    """获取表单文件列表"""
    try:
        # 获取表单目录路径
        forms_dir = os.path.join('data', 'forms')
        
        # 确保目录存在
        if not os.path.exists(forms_dir):
            os.makedirs(forms_dir, exist_ok=True)
            return jsonify({
                'code': 0,
                'message': 'success',
                'data': []
            })
        
        # 获取所有json文件
        form_files = []
        for file in os.listdir(forms_dir):
            if file.endswith('.json'):
                form_files.append({
                    'name': os.path.splitext(file)[0],  # 文件名（不含扩展名）
                    'path': os.path.join('data', 'forms', file)  # 相对路径
                })
        
        return jsonify({
            'code': 0,
            'message': 'success',
            'data': form_files
        })
    except Exception as e:
        return jsonify({
            'code': 1,
            'message': f'获取表单列表失败: {str(e)}',
            'data': None
        }) 